package cn.haoma.base.common;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ProgressBar;

import com.umeng.analytics.MobclickAgent;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import cn.haoma.base.R;
import cn.haoma.base.utils.NullUtil;
import cn.haoma.base.utils.ToastUtil;
import cn.haoma.base.http.HttpHelper;

/**
 * 支持通过ID进行注解,初始化注解过ID的View
 * <p/>
 * 简化findViewById(...)方法->f(...)
 * <p/>
 * 支持String，Collection， Map的判空和Equals判断（不用先做Null判断了）简化方法eq()->equals(), em()->isEmpty()
 * <p/>
 * 跳转Activity时，屏蔽当前Activity的触屏事件，防止产生重复点击问题
 */
public class BaseActivity extends FragmentActivity implements View.OnClickListener {
    /**
     * 刷新页面数据
     */
    public static final int REQUEST_CODE_FRESH_DATA = 888;
    /**
     * 结束当前页面
     */
    public static final int REQUEST_CODE_FINISH = 999;


    private boolean blockTouchEvent;
    private Dialog loadingDialog;

    public void cancelLoadingDialog() {
        try {
            if (null != loadingDialog && loadingDialog.isShowing()) {
                loadingDialog.dismiss();
            }
        } catch (Exception e) {
            loadingDialog = null;
        }

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (blockTouchEvent) {
            return false;
        } else {
            return super.dispatchTouchEvent(ev);
        }
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
        super.startActivityForResult(intent, requestCode, options);
        blockTouchEvent(true);
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    /**
     * @param block onResume()会自动调用此方法 blockTouchEvent(true)
     */
    final protected void blockTouchEvent(boolean block) {
        blockTouchEvent = block;
    }

    final protected boolean em(@Nullable String str) {
        return NullUtil.em(str);
    }

    /**
     * @param map
     * @return return true if map==null or map.size()==0
     */
    final protected boolean em(@Nullable Map map) {
        return NullUtil.em(map);
    }

    /**
     * @return
     * @attention 两个参数都为null返回true
     */
    final protected boolean eq(@Nullable Object obj1, @Nullable Object obj2) {
        return NullUtil.eq(obj1, obj2);
    }

    /**
     * 调用 v.findViewById(id)
     *
     * @param id
     * @param v
     */
    public <T extends View> T f(int id, View v) {
        return (T) v.findViewById(id);
    }

    /**
     * 隐藏软键盘
     */
    public void hideSoftKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        View v = getCurrentFocus();
        if (null != v && null != v.getWindowToken()) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }

    }

    final public boolean isEmp(Collection c) {
        return null == c || c.isEmpty();
    }

    protected boolean isInLoadingMode() {
        return null != loadingDialog && loadingDialog.isShowing();
    }

    @Override
    public void onClick(View view) {
        List<Fragment> fragmentList = getSupportFragmentManager().getFragments();
        if (!em(fragmentList)) {
            for (Fragment fragment : fragmentList) {
                if (fragment instanceof View.OnClickListener) {
                    ((View.OnClickListener) fragment).onClick(view);
                }
            }
        }
    }

    /**
     * @param collection
     * @return return true if collection==null or collection.size()==0
     */
    final protected boolean em(@Nullable Collection collection) {
        return NullUtil.em(collection);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Window window = getWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);//通知栏透明
            //            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);//下面三个虚拟按键透明
        }
        window.requestFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        loadView();
    }

    private void loadView() {
        if (getClass().isAnnotationPresent(LayoutId.class)) {
            setContentView(getClass().getAnnotation(LayoutId.class).value());
            ArrayList<Field> fieldList = new ArrayList<>();
            Class clazz = getClass();
            while (clazz != Object.class) {
                Field[] fields = getClass().getDeclaredFields();
                fieldList.addAll(Arrays.asList(fields));
                clazz = clazz.getSuperclass();
            }
            Field f = null;
            try {
                for (Field field : fieldList) {
                    if (field.isAnnotationPresent(Id.class)) {
                        f = field;
                        field.setAccessible(true);
                        field.set(this, findViewById(field.getAnnotation(Id.class).value()));
                    }
                }
            } catch (ClassCastException e) {
                Log.e(BaseActivity.class.getName(), "转型异常:" + f.getName() + "是" + f.getType());
                throw new IllegalStateException();
            } catch (NullPointerException e) {
                Log.e(BaseActivity.class.getName(), "控件未找到，请检查View声明的类型");
            } catch (Exception e) {
                Log.e(BaseActivity.class.getName(), Arrays.toString(e.getStackTrace()));
            }
        }
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        blockTouchEvent(false);
        MobclickAgent.onResume(this);
    }

    /**
     * setGone
     * 设置View[]为不可见gone
     *
     * @param views
     */
    public void sg(View... views) {
        for (View v : views) {
            v.setVisibility(View.GONE);
        }
    }

    public void sg(int... viewIds) {
        for (int id : viewIds) {
            f(id).setVisibility(View.GONE);
        }
    }

    /**
     * 调用 findViewById(id)
     *
     * @param id
     */
    public <T extends View> T f(int id) {
        return (T) findViewById(id);
    }

    public Dialog showLoadingDialog() {
        if (null == loadingDialog) {
            loadingDialog = new Dialog(this) {
                @Override
                public void onBackPressed() {
                    finish();
                    HttpHelper.cancelAllRequest();
                }
            };
            final Window window = loadingDialog.getWindow();
            window.requestFeature(Window.FEATURE_NO_TITLE);
            window.setBackgroundDrawable(new ColorDrawable(0));
            loadingDialog.setContentView(new ProgressBar(this));
            loadingDialog.setCanceledOnTouchOutside(false);
            loadingDialog.setCancelable(false);
        }
        loadingDialog.show();
        return loadingDialog;
    }

    /**
     * 强制弹出软键盘
     *
     * @param view
     */
    public void showSoftKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
    }

    protected void showToast(Object obj) {
        ToastUtil.showShortToast(this, obj);
    }

    /**
     * setInvisiable
     * 设置View[]为不可见invisiable
     *
     * @param views
     */
    public void si(View... views) {
        for (View v : views) {
            v.setVisibility(View.INVISIBLE);
        }
    }

    public void si(int... viewIds) {
        for (int id : viewIds) {
            f(id).setVisibility(View.INVISIBLE);
        }
    }

    /**
     * setVisiable
     * 设置View[]为可见visiable
     *
     * @param views
     */
    public void sv(View... views) {
        for (View v : views) {
            v.setVisibility(View.VISIBLE);
        }
    }

    public void sv(int... viewIds) {
        for (int id : viewIds) {
            f(id).setVisibility(View.VISIBLE);
        }
    }
    /**
     * 获取屏幕分辨率
     *
     * @return
     */
    public Point getScreenPoint()
    {
        DisplayMetrics outMetrics = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        Point p = new Point(outMetrics.widthPixels, outMetrics.heightPixels);
        return p;
    }

}
